﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel.Design;

using InfFront.InfoSources.Base;
using InfFront.InfoSources.Base.Design;

namespace InfFront.InfoSources.ADO.Design
{
    public class DataTableInfoSourceDesignTimeExtension: InfoSourceDesignTimeExtension
    {
        public DataTableInfoSourceDesignTimeExtension()
        {
            AddAction(new AutogenerateFieldsAction(this));
        }

        private class AutogenerateFieldsAction: InfoSourceDesignTimeAction
        {
            public AutogenerateFieldsAction(DataTableInfoSourceDesignTimeExtension owner)
                : base(owner)
            {
                this.Caption = "Fill by table scheme";
                this.Target = InfoSourceDesignTimeActionTarget.Fields;
            }

            public override void Execute()
            {
                var source = (DataTableInfoSource)Owner.Designer.Component;
                var table = source.DataTable;
                if (table == null)
                    return;
                var sp = (IServiceProvider)Owner.Designer.Component.Site;
                var dHost = (IDesignerHost) sp.GetService(typeof(IDesignerHost));

                foreach (DataColumn col in table.Columns)
                {
                    var fld = (DataColumnInfoField)dHost.CreateComponent(typeof(DataColumnInfoField));
                    fld.Title = col.Caption;
                    fld.ColumnName = col.ColumnName;
                    var type = col.DataType;

                    if      (type.Equals(typeof(DateTime)))
                        fld.DataTypeKind = BaseDataType.Type.DateTime;
                    else if (type.Equals(typeof(bool)))
                        fld.DataTypeKind = BaseDataType.Type.Boolean;
                    else if (type.Equals(typeof(double)))
                        fld.DataTypeKind = BaseDataType.Type.Float;
                    else if (type.Equals(typeof(int)))
                        fld.DataTypeKind = BaseDataType.Type.Integer;
                    else if (type.Equals(typeof(string)))
                        fld.DataTypeKind = BaseDataType.Type.String;
                    else
                        System.Diagnostics.Debug.Assert(false);
                }
            }
        }
    }
}
